<!doctype html>

<html lang="en">
<head>
<meta charset="utf-8" />

<link rel="icon" type="image/png" href="/images/epoolSmall.png" />

<link rel="stylesheet"
	href="http://code.jquery.com/ui/1.10.4/themes/eggplant/jquery-ui.css" />
<script type='text/javascript' src='https://www.google.com/jsapi'></script>

<script type="application/ecmascript" async="" src="/js/FileSaver.js"></script>

<script
	src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCrxmbr62tBd5dYO4X8timp7fSxq-rlQwA&sensor=false&libraries=visualization"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<script>
	function saveXML() {
		if (tweets == null)
			alert(" no data to save");
		else {
			var blob = new Blob([ tweets ], {
				type : "text/plain;charset=utf-8"
			});
			saveAs(blob, "geoTweets.xml");
		}
	}
</script>

<script>
	function saveCSV() {
		if (tweets == null)
			alert(" no data to save");
		else {
			var blob = new Blob([ tweets ], {
				type : "text/plain;charset=utf-8"
			});
			saveAs(blob, "geoTweets.csv");
		}
	}
</script>

<script>
	var tweets;
	function lookupTweet(query) {
		var tweetCount = 0;
		document.getElementById('tweetServletResponse').innerHTML = " ";

		jQuery
				.ajax({
					type : "POST",
					url : "/twitterXML.groovy",
					cache : false,
					data : "query=" + query + "&distance=" + distance.value,
					success : function(xml) {
						jQuery(xml).find('tweet').each(
								function() {
									tweetCount++;
									var sText = jQuery(this).find('text')
											.text();
									jQuery("<li></li>").html(
											'Tweet Text: ' + sText).appendTo(
											'#tweetServletResponse');
								});
						tweets = xml;
						document.getElementById('tweetCount').innerHTML = "Geocoded tweet count: "
								+ tweetCount;
						if (tweetCount < 1)
							//alert ("no goecoded tweets found");
							document.getElementById('tweetServletResponse').innerHTML = "<p> No geocoded tweets found for query </p>";
					},
					error : function(jqXHR, textStatus, errorThrown) {
						alert("error " + textStatus + " errorThrown is: "
								+ errorThrown);
					}
				});
	}
</script>

<link rel="icon" type="image/png" href="epoolSmall.png" />

<script>
	jQuery(function() {
		jQuery("#tabs").tabs();
		jQuery('#tabs').tabs("option", "active", 0);
	});
</script>

<script type='text/javascript'>
	google.load('visualization', '1', {
		packages : [ 'gauge' ]
	});
	google.setOnLoadCallback(drawChart);
	function drawChart() {
		var data = google.visualization.arrayToDataTable([
				[ 'Label', 'Value' ], [ 'Threat Level', 80 ],
				[ 'Confidence', 55 ] ]);

		var options = {
			width : 400,
			height : 120,
			redFrom : 90,
			redTo : 100,
			yellowFrom : 75,
			yellowTo : 90,
			minorTicks : 5
		};

		var chart = new google.visualization.Gauge(document
				.getElementById('chart_div'));
		chart.draw(data, options);
	}
</script>

<script>
	jQuery(function() {
		var geocoder;
		var lat, lng;
		var map, pointarray, heatmap;
		var crimeType = "all";

		var crimeData = [];

		function drawMap() {
			//latlng = new google.maps.LatLng(53.37674, -1.468016);
			latlng = new google.maps.LatLng(51.50851, -0.125487);
			lat = 51.50851;
			lng = -0.125487;
			pointarray = [];
			crimeData = [];
			latlng = new google.maps.LatLng(lat, lng);
			var mapOptions = {
				zoom : 15,
				center : latlng,
				mapTypeId : google.maps.MapTypeId.SATELLITE
			};

			map = new google.maps.Map(document.getElementById('map-canvas'),
					mapOptions);

			var policeUrl = "http://data.police.uk/api/crimes-street/all-crime?lat="
					+ lat + "&lng=" + lng;

			if (crimeType != "no")
				jQuery.getJSON(policeUrl, function(data) {

					jQuery.each(data, function(key, val) {
						var myLatlng = new google.maps.LatLng(
								val.location.latitude, val.location.longitude);
						if (crimeType == "all" || val.category == crimeType)
							crimeData.push(myLatlng);

						//console.log ("category is : " + val.category);
					});

					var pointArray = new google.maps.MVCArray(crimeData);
					console.log("pointarray size: " + pointArray.length);
					console.log("crime data size at end: " + crimeData.length);

					heatmap = new google.maps.visualization.HeatmapLayer({
						data : pointArray
					});

					heatmap.setMap(map);
				});

			addMarkers();
		}

		function addMarkers() {
			console.log("in add markers");

			var thbImage = {
				url : 'thb.png',
				// This marker is 20 pixels wide by 32 pixels tall.
				size : new google.maps.Size(32, 32),
				scaledSize : new google.maps.Size(30, 30),
				// The origin for this image is 0,0.
				origin : new google.maps.Point(0, 0),
				// The anchor for this image is the base of the flagpole at 0,32.
				anchor : new google.maps.Point(0, 32)
			};

			var drugsImage = {
				url : 'drugs.png',
				size : new google.maps.Size(32, 32),
				scaledSize : new google.maps.Size(30, 30),
				origin : new google.maps.Point(0, 0),
				anchor : new google.maps.Point(0, 32)
			};

			// var ocLatlng = new google.maps.LatLng(53.377127, -1.467705);

			var OCurl = //"http://searchbroker.azurewebsites.net/SearchBroker.ashx?lat=111&lng=222";
			//   "/threat.json"; 
			//"/EARE_Threats2.json"
			"/DPN_Threats2.json";
			
			console.log("before getjosn 2");
			var threatImage;

			jQuery.getJSON(OCurl, function(data) {

				console.log("data: " + data);

				jQuery.each(data, function(key, val) {
					var OCLatlng = new google.maps.LatLng(
							val.geoData.longitude, val.geoData.latitude);
					//if (crimeType=="all"  ||val.category==crimeType)		
					// crimeData.push(myLatlng);

					console.log("lat is : " + val.geoData.latitude
							+ " longi is " + val.geoData.longitude);
					//console.log ("crime dat size: " + crimeData.length);

					//  if (val.crimeCategory=="cocaine trafficking") {
					threatImage = drugsImage;
					//    }
					//  else  { //if (val.crimeCategory=="human_trafficking"){
					//  threatImage=thbImage;
					//    };

					console.log(" val desc: " + val.description
							+ " val.source.descriptoin"
							+ val.source.description);
					console.log(" val palce: " + val.geoData.place);

					var infoString = '<p style="color:blue;"> Description: '
							+ val.description + '</p>'
							+ '<p style="color:green;"> Source: '
							+ val.source.description + '</p>'
							+ '<p style="color:red;"> Alert Level: '
							+ val.alertLevel + '</p>';

					var infowindow = new google.maps.InfoWindow({
						content : infoString
					});

					var marker2 = new google.maps.Marker({
						position : OCLatlng,
						map : map,
						icon : threatImage,
						title : val.crimeType
					});

					google.maps.event.addListener(marker2, 'click', function() {
						infowindow.open(map, marker2);
					});
				});
			});
		}

		function codeAddress() {

			geocoder = new google.maps.Geocoder();
			var address = document.getElementById('address').value;
			console.log("address is " + address);
			geocoder
					.geocode(
							{
								'address' : address
							},
							function(results, status) {
								console.log("status " + status);

								if (status == google.maps.GeocoderStatus.OK) {
									console.log(" formattedloc "
											+ results[0].formatted_address);
									var location = results[0].geometry.location;

									lat = location.lat();
									lng = location.lng();
									console.log(" lat is " + lat + " long is "
											+ lng);
									drawMap();

								} else {
									alert('Geocode was not successful for the following reason: '
											+ status);
								}
							});
		}

		jQuery("#address").change(
				function() {

					console.log("address value: "
							+ document.getElementById('address').value);
					codeAddress();
				});

		jQuery("#crimeType").change(function() {
			crimeType = jQuery(".crimeType option:selected").val();
			console.log("crimeType is: " + crimeType);
			drawMap();

			//if (document.getElementById('address').value !==null 
			//    && document.getElementById('address').value!==undefined
			//         && document.getElementById('address').value!=="")
			//      {
			//		codeAddress();
			//	  }
		});

		jQuery("#city").change(function() {
			cityName = jQuery(".citySelect option:selected").val();
			console.log("city name: " + cityName);
		});

		jQuery("#time").change(function() {
			time = jQuery(".timeSelect option:selected").val();
			console.log("time is " + time);
		});

		jQuery("#showMap").click(function() {
			drawMap();
			console.log("showMap selected");
		});

	});
</script>

<style>
#map-canvas {
	width: 800px;
	height: 700px;
}

body {
	font-family: arial; /* Font */
	font-size: 12px; /* Font Size */
}
</style>

</head>
<body>
	<h1>Organised Crime Visual Alarm Tool</h1>
	<div id="tabs">
		<ul>
			<li><a href="#tabs-1">View UK crime data</a></li>
			<li><a href="#tabs-2">Analyse OC threats</a></li>
			<li><a href="#tabs-3">New threat submission area</a></li>
			<li><a href="#tabs-4">Analyze Geocoded Tweets</a></li>
		</ul>
		<div id="tabs-1">
			<p>Enter UK city or postcode to see crime on map. If you select
				Sheffield you will see potential OC threat on the same map</p>
			<button type="button" id="showMap">Show Map</button>


			<label for="threatSelect">Show crime layer:</label> <select
				class="crimeType" id="crimeType" title="Crime Type">
				<option value="no">Do not show crime layer</option>
				<option value="all">All Crime</option>
				<option value="drugs">drugs</option>
				<option value="no">Do not show crime layer</option>
			</select> </select> <label for="timeSelect">Time Period:</label> <select
				class="threatSelect ui-state-disabled" class="timeSelect" id="time"
				title="select time period">
				<option value="oct">October</option>
				<option value="nov">November</option>
				<option value="dec" disabled>December</option>

			</select>

			<div id="map-canvas"></div>
		</div>
		<div id="tabs-3">
			<p>Select parameters and submit details of new/emerging threat</p>
			<label for="citySelect">City:</label> <select class="citySelect"
				id="city" title="select city">
				<option value="Sheffield">Sheffield</option>
				<option value="Paris">Paris</option>
				<option value="Madrid" disabled>Madrid</option>
			</select> <label for="timeSelect">Time Period:</label> <select
				class="timeSelect" id="time" title="select time period">
				<option value="oct">October</option>
				<option value="nov">November</option>
				<option value="dec" disabled>December</option>
			</select> <label for="threatSelect">Crime Type:</label> <select
				class="threatSelect ui-state-disabled" id="threat"
				title="Crime Type">
				<option value="drugs">Drugs</option>
				<option value="people">People Trafficking</option>
				<option value="guns">Guns</option>
			</select> <label for="alertLevelSelect">Alert Level:</label> <select
				class="alertLevelSelect ui-state-disabled" id="level"
				title="Alert Level">
				<option value="high">High</option>
				<option value="medium">Medium</option>
				<option value="low">Low</option>
			</select>
			<p>
				longitude (if known):<input> latitude (if known):<input>
			</p>

			<p>
				<label for="comments">Comments:</label>
				<textarea rows="4" cols="50" class="comments"
					title="Enter details of threat here"> </textarea>
			</p>

			<button title="click here to submit details of a new threat">
				Submit threat details</button>
		</div>
		<div id="tabs-2">
			<p>OC threat data - in development</p>
			<div id='chart_div'></div>
		</div>
		<div id="tabs-4">


			</head>
			<h1>Organised Crime Visual Alarm Tool</h1>
			<h2>Search Geocoded Tweets</h2>
			<hr />
			<hr />
			<p>
				1. Query/hash tag: <input type="text" id="query"></input>
			</p>
			<p>
				2. Tweets within :<input type="text" id="distance"></input> km of
				Sheffield
			</p>
			<button onclick="lookupTweet(query.value)">3. Lookup Tweets</button>
			<p>
				Tweet details : <span id="tweetCount"></span></span> <span
					id="tweetServletResponse"></span>
			</p>

			<br>
			<button onclick="saveXML()">4. Save XML to File</button>

		</div>
</body>
</html>